package com.itheima.advice;
//这个是通知类   就是aop对业务层进行方法增强的类


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;

import org.junit.Test;
import org.springframework.stereotype.Component;


import java.io.*;
import java.util.Date;

@Component
@Aspect
public class MyAdviceClass {


    //时间
    private long runtime;
    private long overtime;

    //方法名
    String methodname;
    //时间
    Date date;


    //配置service包下所有子包所有类的所有方法都进行切面编程
    @Pointcut("execution(* com.itheima.service..* .*(..))")
    public void pt(){}
    //方法前获取毫秒值
   //@Before("pt()")
    public void getRunTime(){
       System.out.println("进行增强的通知");
    runtime = System.currentTimeMillis();

}


   //方法后获取毫秒值并写log文件到磁盘
   //@After("pt()")
    public  void getOverTime() throws Throwable {
         date = new Date();

        overtime = System.currentTimeMillis();


        //共计消耗时间
        long l=(overtime-runtime);
        String path="D:/log.txt";
        File file = new File(path);
        //如果没有文件就创建一个
        if(!file.exists()){
            file.createNewFile();
        }
       FileOutputStream fileOutputStream=new FileOutputStream(path,true);
       OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
       PrintWriter pw = new PrintWriter(outputStreamWriter);
        System.out.println("日志文件已经保存到"+path+"中");
       //输出加手动换行
       pw.print(date+":       执行的方法是: "+methodname+"       一共消耗时间是: "+l+"毫秒"+""+"\r\n");
       pw.flush();
       pw.close();

   }




    @Around("pt()")
    public void around(ProceedingJoinPoint pdj ){

        try {
            getRunTime();
            pdj.proceed();
            methodname = pdj.getSignature().getName();
            getOverTime();



        } catch (Throwable throwable) {
            throwable.printStackTrace();




        }


    }


}
